"""
==========================================
Author:不二
Time:2020/5/8
==========================================
"""
import os
import time
import datetime
from Common.handle_log import do_log
from Common.handle_path import SCREENSHOT_DIR
from Common.handle_path import QRCODE_DIR
# from Common.connect_to_device import d  # 全局驱动 d 重要，勿删！


class BasePage:
    # def __init__(self, driver):
    #     self.d = driver

    # 将 'd(text="电影")'  转换为 d(text="电影")
    def get_element(self, loc):
        try:
            ele = eval(loc)
        except:
            do_log.exception("{} 元素表达式格式错误无法转换".format(loc))
            raise
        else:
            return ele

    # 等待元素存在
    def wait_ele_exists(self, loc, img_desc, timeout=3):
        start = datetime.datetime.now()  # 用datetime模块获取时间
        try:
            ele = self.get_element(loc)
            if not (ele.exists(timeout=timeout)):
                raise Exception
        except:
            do_log.exception("等待 {} 元素 {} 存在失败！".format(img_desc, loc))
            if '.child(textMatches=".+")' in loc:  # 文本获取失败，不用截图
                pass
            else:
                self.save_img(img_desc)
            raise
        else:
            end = datetime.datetime.now()  # 用datetime模块获取当前时间
            do_log.info("等待 {} 元素 {} 存在成功。耗时：{}".format(img_desc, loc, end - start))

    def wait_ele_gone(self, loc, img_desc, timeout=60):
        start = datetime.datetime.now()  # 用datetime模块获取时间
        try:
            ele = self.get_element(loc)
            if not (ele.wait_gone(timeout=timeout)):
                raise Exception
        except:
            do_log.exception("等待 {} 元素 {} 消失失败！".format(img_desc, loc))
            self.save_img(img_desc)
            raise
        else:
            end = datetime.datetime.now()  # 用datetime模块获取当前时间
            do_log.info("等待 {} 元素 {} 消失成功。耗时：{}".format(img_desc, loc, end - start))

    # 判断当前页面元素是否存在
    def judge_ele_exists(self, loc):
        ele = self.get_element(loc)
        if ele.exists:
            do_log.info("{} 元素在当前界面中存在".format(loc))
            return True
        else:
            do_log.info("{} 元素在当前界面中不存在".format(loc))
            return False

    # 先等待当前页面元素
    def _deal_element(self, loc, img_desc, timeout=3):  # 为了加速测试修改为3秒
        self.wait_ele_exists(loc, img_desc, timeout=timeout)
        return self.get_element(loc)

    # 点击元素
    def click_element(self, loc, img_desc, timeout=10):
        ele = self._deal_element(loc, img_desc, timeout=timeout)
        try:
            ele.click()
            do_log.info("点击 {} 元素 {} 成功！".format(img_desc, loc))
        except:
            do_log.exception("点击 {} 元素 {} 失败!".format(img_desc, loc))
            self.save_img(img_desc)
            raise

    # 截图
    def save_img(self, img_description):
        """
        :param img_description: 图片的描述 。格式为 页面名称_功能名
        :return:
        """
        now = time.strftime("%Y-%m-%d %H_%M_%S")
        file_path = "{}_{}.jpg".format(now, img_description)
        img_path = os.path.join(SCREENSHOT_DIR, file_path)
        try:
            d.screenshot(img_path)
        except:
            do_log.exception("截图失败！")
        else:
            do_log.info("截图成功，截图存放在：{}".format(img_path))

    # 录制视频
    def save_video(self, video_time, video_description):
        now = time.strftime("%Y-%m-%d %H_%M_%S")
        file_path = "{}_{}.mp4".format(video_description, now)
        video_path = os.path.join(SCREENSHOT_DIR, file_path)
        try:
            d.screenrecord(video_path)
            time.sleep(video_time)
            d.screenrecord.stop()
        except:
            do_log.exception("录制视频失败！")
        else:
            do_log.info("录制视频成功，视频存放在：{}".format(video_path))

    # 截图-专用于发送微信扫码使用,截图文件名要是英文或数字.jpg 不然无法发送,并且需要将保存路径返回便于发送
    def save_jpg(self, img_description):
        """
        :param img_description: 图片的描述 。格式为 只能是英文或数字
        :return:
        """
        now = time.strftime("%Y-%m-%d %H_%M_%S")
        file_path = "{}_{}.jpg".format(img_description, now)
        img_path = os.path.join(QRCODE_DIR, file_path)
        try:
            d.screenshot(img_path)
        except:
            do_log.exception("网页截图失败！")
        else:
            do_log.info("截图成功，截图存放在：{}".format(img_path))
            return img_path

    # 获取元素的属性值
    def get_element_attribute(self, loc, attr_name, img_desc, timeout=10):
        ele = self._deal_element(loc, img_desc, timeout=timeout)
        try:
            # info_value = ele.info
            attr_value = ele.info[attr_name]
        except:
            do_log.exception("获取 {} 元素 {} 的属性 {} 失败! ".format(img_desc, loc, attr_name))
            self.save_img(img_desc)
            raise
        else:
            # do_log.info("获取 {} 元素 {} 的属性 {} 值为:{}".format(img_desc, loc, attr_name, info_value))
            do_log.info("获取 {} 元素 {} 的属性 {} 值为:{}".format(img_desc, loc, attr_name, attr_value))
            return attr_value

    # 获取元素的文本值
    def get_text(self, loc, img_desc, timeout=3):
        ele = self._deal_element(loc, img_desc, timeout=timeout)
        try:
            text = ele.get_text()
        except:
            # 日志
            do_log.exception("获取 {} 元素 {} 的文本失败！".format(img_desc, loc))
            # 截图
            # self.save_img(img_desc)
            raise
        else:
            do_log.info("获取 {} 元素 {} 的文本值为:{}".format(img_desc, loc, text))
            return text

    # 输入文本
    def input_text(self, loc, value, img_desc, timeout=10):
        ele = self._deal_element(loc, img_desc, timeout=timeout)
        try:
            ele.set_text(value)
            do_log.info("在 {} 元素 {} 上输入文本值: {} 成功！".format(img_desc, loc, value))
        except:
            do_log.exception("在 {} 元素 {} 上输入文本值: {} 失败！".format(img_desc, loc, value))
            self.save_img(img_desc)
            raise

    # # 判断焦点是否在元素上-通过selected属性
    # def judge_ele_selected(self, loc, img_desc):
    #     if self.judge_ele_exists(loc):
    #         ele = self.get_element(loc)
    #         if ele.info['selected']:
    #             do_log.info("当前焦点在 {} 元素上")
    #         return ele.info['selected']
    #     else:
    #         do_log.exception("{}元素在界面上不存在，无法确定焦点，请检查截图".format(img_desc))
    #         self.save_img(img_desc)
    #         raise

    # 判断焦点是否在元素上-通过selected属性
    def judge_ele_selected(self, loc, img_desc):
        if self.judge_ele_exists(loc):
            # ele = self.get_element(loc)
            if self.get_element_attribute(loc, 'selected', img_desc):
                do_log.info("当前焦点在 {} 元素上".format(loc))
                return True
            else:
                do_log.info("当前焦点不在 {} 元素上".format(loc))
                return False
        else:
            do_log.exception("{} 元素在界面上不存在，无法确定焦点，请检查截图".format(loc))
            self.save_img(img_desc)
            raise

    def press_key(self, key):
        if key == "left":
            try:
                d.press("left")
            except:
                do_log.exception("遥控器按 ← 键失败")
                raise
            else:
                do_log.info("遥控器按 ← 键成功")
        if key == "right":
            try:
                d.press("right")
            except:
                do_log.exception("遥控器按 → 键失败")
                raise
            else:
                do_log.info("遥控器按 → 键成功")
        if key == "up":
            try:
                d.press("up")
            except:
                do_log.exception("遥控器按 ↑ 键失败")
                raise
            else:
                do_log.info("遥控器按 ↑ 键成功")
        if key == "down":
            try:
                d.press("down")
            except:
                do_log.exception("遥控器按 ↓ 键失败")
                raise
            else:
                do_log.info("遥控器按 ↓ 键成功")
        if key == "home":
            try:
                d.press("home")
            except:
                do_log.exception("遥控器按 home 键可能成功")
                # raise launcher很特殊，按 home 键会报错，所以这里不管报错，日志都写成功
            else:
                do_log.info("遥控器按 home 键成功")
        if key == "back":
            try:
                result = d.press("back")
            except:
                do_log.exception("遥控器按 back 键失败")
                raise
            else:
                do_log.info("遥控器按 back 键成功")
                return result
        if key == "enter":
            try:
                d.press("enter")
            except:
                do_log.exception("遥控器按 enter 键失败")
                raise
            else:
                do_log.info("遥控器按 enter 键成功")
        if key == "menu":
            try:
                d.press("menu")
            except:
                do_log.exception("遥控器按 menu 键失败")
                raise
            else:
                do_log.info("遥控器按 menu 键成功")

    def start_CPdemo_app(self):
        try:
            d.app_start("com.arcvideo.totalmedia.cpuidemo.IQY", wait=True)
        except:
            do_log.exception("启动CPdemo失败")
        else:
            do_log.info("启动CPdemo成功")

    def wait_for_activity(self, activity, img_desc, timeout=10):
        if d.wait_activity(activity, timeout=timeout):
            do_log.info("等待 {} activity 页面加载 成功".format(img_desc))
            return True
        else:
            do_log.exception("等待 {} activity页面加载 失败".format(img_desc))
            return False

    def get_app_current(self):
        current_app = d.app_current()
        do_log.info("当前前台运行程序为{}".format(current_app))
        return current_app

    def get_ele_center(self, loc, img_desc, timeout=10):
        ele = self._deal_element(loc, img_desc, timeout=timeout)
        try:
            x, y = ele.center()
        except:
            # 日志
            do_log.exception("获取 {} 元素 {} 的中心位置坐标失败！".format(img_desc, loc))
            # 截图
            self.save_img(img_desc)
            raise
        else:
            do_log.info("获取 {} 元素 {} 中心位置坐标为:{},{}".format(img_desc, loc, x, y))
            return x, y

    def install_app(self, path):
        try:
            d.app_install(data=path)
        except:
            do_log.exception("推送 {} app 安装失败!".format(path))
            raise
        else:
            do_log.info("推送 {} app 安装成功!".format(path))

    def click_point(self, x, y, img_desc):
        try:
            d.click(x, y)
            do_log.info("点击 {} 坐标点{},{}成功！".format(img_desc, x, y))
        except:
            do_log.exception("点击 {} 坐标点{},{}失败！".format(img_desc, x, y))
            self.save_img(img_desc)
            raise


if __name__ == '__main__':
    # import uiautomator2 as u2
    #
    # d = u2.connect('192.168.10.163')
    # loc = "d(resourceId='com.dangbei.leard.leradlauncher:id/main_title_view_search_tpv')"
    # textpage.save_img("测试截图")
    # textpage.click_element(loc, "首页_点击搜索")
    # print(textpage.judge_ele_exists(loc))
    # loc_1 = "d(text='应用')"
    # textpage.get_element_attribute(loc_1, "selected", "首页_应用的焦点属性")
    # loc_2 = "d(resourceId='com.dangbei.leard.leradlauncher:id/main_day_weather_tv')"
    # textpage.get_text(loc_2, "首页_天气文本值")
    # ser_loc = "d(resourceId='com.dangbei.leard.leradlauncher:id/view_search_key_board_search_et')"
    # textpage.input_text(ser_loc, "我是余欢水", "搜索页面_搜索 我是余欢水")
    # loc = 'd(text="云视听极光")'
    # # res = BasePage().judge_ele_selected(loc, "主页_查看焦点是否在-全部频道")
    # x, y = BasePage().get_ele_center(loc, "获取 云视听极光 坐标")
    # print(type(x))
    # print(type(y))
    # BasePage().save_img("精选")
    # BasePage().save_video(5,"666")
    # while True:
    #     BasePage().press_key("enter")
    # BasePage().save_img("测试截图")
    # loc = "d(selected=True,textContains='删除全部记录')"
    res = d(resourceId="com.arcvideo.totalmedia.cpuidemo.IQY:id/seekBar").info
    res2 = d(resourceId="com.arcvideo.totalmedia.cpuidemo.IQY:id/seekBar").center()
    pass
